<?php

namespace App\Console\Commands\PushCenter;

use App\Repositories\Push\PushLogRepository;
use App\Repositories\Push\PushRepository;
use App\Repositories\User\UserRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Services\Wechat;
use Illuminate\Support\Facades\DB;

/**
 * Class CheckVipIsExpire
 * @package App\Console\Commands\User
 */
class CreateTask extends Command
{

    protected $signature = 'pushCenter:createTask';

    protected $description = 'push center create task';

    private $pushRepository;
    
    private $userRepository;

    private $pushLogRepository;

    private $wx;

    private $datetime;

    private $logger;

    /**
     * CreateTask constructor.
     * @param PushRepository $pushRepository
     * @param UserRepository $userRepository
     * @param PushLogRepository $pushLogRepository
     */
    public function __construct(
        PushRepository $pushRepository,
        UserRepository $userRepository,
        PushLogRepository $pushLogRepository)
    {
        parent::__construct();

        $this->pushRepository = $pushRepository;
        
        $this->userRepository = $userRepository;

        $this->pushLogRepository = $pushLogRepository;

        $this->logger = Log::channel('console');

        $this->wx = new Wechat();

        $this->datetime = (new Carbon())->toDateTimeString();
    }

    /**
     * @param $push
     * @param $uid
     * @return array
     */
    private function generateLog($push, $uid)
    {
        return [
            'push_id'  => $push->id,
            'uid'      => $uid,
            'content'  => $push->title,
            'datetime' => $this->datetime
        ];
    }

    /**
     * @param $push
     */
    private function createTask($push)
    {
        $lastId = 0;

        $pushLog = [];

        $i = 0;
        while(1) {
            $userIds = $this->userRepository->getUserIdsByPush($push, $lastId);

            $waddress='';
            $wli='';
            //获取备注行业的uid开始
            if($push->province_id == 'all'){
                $waddress=' AND a.`remark_address` != ""';
            }else if($push->province_id){
                list($province, $city) = explode(' ', $push->address);
                if ($push->city_id == 'all'){
                    $waddress=' AND (a.`remark_address` LIKE "%'.$province.'" OR a.`remark_c_address` LIKE "%'.$province.'")';
                }else{
                    $waddress=' AND (a.`remark_address` like "%'.$city.'%" OR a.`remark_c_address` LIKE "%'.$city.'%")';
                }
            }

            if($push->industry_ids && $push->label_ids){
                $labelIds = explode(',', $push->label_ids);
                $industryIds_ori = explode(',', $push->industry_ids);

                $industryIds_count=floor(count($industryIds_ori)/3);
                $industryIds=array();
                for($i=0;$i<$industryIds_count;$i++){
                    if(!empty($industryIds_ori[2+$i*3])){
                        $industryIds[]='"'.$industryIds_ori[2+$i*3].'"';
                    }else if(!empty($industryIds_ori[1+$i*3])){
                        $industryIds[]='"'.$industryIds_ori[1+$i*3].'"';
                    }else if(!empty($industryIds_ori[$i*3])){
                        $industryIds[]='"'.$industryIds_ori[$i*3].'"';
                    }
                }

                $industryIds=implode(",",$industryIds);
                $labelIds=implode(",",$labelIds);
                $wli=' AND (a.`remark_industry_id` IN ('.$industryIds.') OR b.`label_id` IN ('.$push->label_ids.'))';

            }else{
                if ($push->industry_ids) {
                    $industryIds_ori = explode(',', $push->industry_ids);
                    $industryIds_count=floor(count($industryIds_ori)/3);
                    $industryIds=array();
                    for($i=0;$i<$industryIds_count;$i++){
                        if(!empty($industryIds_ori[2+$i*3])){
                            $industryIds[]='"'.$industryIds_ori[2+$i*3].'"';
                        }else if(!empty($industryIds_ori[1+$i*3])){
                            $industryIds[]='"'.$industryIds_ori[1+$i*3].'"';
                        }else if(!empty($industryIds_ori[$i*3])){
                            $industryIds[]='"'.$industryIds_ori[$i*3].'"';
                        }
                    }
                    $industryIds=implode(",",$industryIds);
                    $wli=' AND a.`remark_industry_id` IN ('.$industryIds.')';
                }

                if ($push->label_ids) {
                    $wli=' AND b.`label_id` IN ('.$push->label_ids.')';
                }

            }


            if ($lastId) {
                $lastIdsql=' AND a.`user_id` > '.$lastId;
            }else{
                $lastIdsql="";
            }


            $remark_uidor=DB::select("SELECT a.`user_id` AS rid FROM midtown_user_remark_log AS a LEFT JOIN midtown_remark_user_label AS b ON a.`user_id` = b.`user_id` WHERE 1 ".$waddress.$wli.$lastIdsql." ORDER BY a.`user_id` ASC");

            $remark_ids=array();
            if(!empty($remark_uidor)){
                foreach($remark_uidor as $k=>$v){
                    $remark_ids[]=$v->rid;
                }
            }else{
                $remark_ids=array();
            }



            if(!empty($remark_ids)){
                $userIdss=array_unique($remark_ids);
                foreach($userIdss as $rk=>$rv){
                    $check_user=array();
                    foreach($userIds as $uidcheck){
                        $check_user[]=$uidcheck;
                    }
                   if(!in_array($rv,$check_user)){
                       $userIds[]=$rv;
                   }
                }
           }




            //file_put_contents('./common2.php',$userIds,FILE_APPEND);
            //获取备注行业的uid结束

          /* if (!empty($userIds)) {

            }else{
                break;
            }*/

            if ($userIds->isEmpty()) {
                break;
            }

             foreach ($userIds as $uid) {
                //file_put_contents("./common3.log",$uid);
                $user = $this->userRepository->getOneById($uid);

                if (!$user) {
                    continue;
                }

                $this->wx->sendWxTplMsg($user->open_id, $push->title, '', $push->url);

                $pushLog[] = $this->generateLog($push, $uid);

                $i++;

                if ($i == 500) {
                    $this->pushLogRepository->insert($pushLog);
                    $pushLog = [];
                }

                $lastId = $uid;
            }

        }



        if ($pushLog) {
            $this->pushLogRepository->insert($pushLog);
        }
    }

    /**
     * @param $pushId
     */
    private function updateCompleteStatus($pushId)
    {
        $logCount = app(PushLogRepository::class)->getCountByPushId($pushId);

        $this->pushRepository->updateCompleteStatus($pushId, $logCount);
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        foreach ($this->pushRepository->getUnGenerateTaskPush() as $row) {

            try {

                app(PushRepository::class)->updateGenerateStatus($row->id);


                $this->createTask($row);

                $this->updateCompleteStatus($row->id);

            } catch (\Exception $e) {

                $this->logger->error($this->signature, [$row, $e]);

                $this->error($e->getMessage());
            }
        }

        $this->info($this->signature . ' success！'. (new Carbon())->toDateTimeString());
    }
}